package Medium;

import java.util.ArrayList;
import java.util.Stack;

public class LC0394 {
    public static String decodeString(String s) {
        if (s.isEmpty()) return s;

        int i = 0;
        ArrayList<Integer> repeats = new ArrayList<>();
        ArrayList<String> decodedStrings = new ArrayList<>();

        while (i < s.length()) {
            if (isNumber(s.charAt(i))) {
                // 计算重复次数
                StringBuilder sb = new StringBuilder();
                while (isNumber(s.charAt(i))) {
                    sb.append(s.charAt(i));
                    i++;
                }
                int repeat = Integer.parseInt(sb.toString());
                repeats.add(repeat);

                // 解码字符串
                Stack<Character> stack = new Stack<>();
                sb = new StringBuilder();
                for (; i < s.length(); ) {
                    if (s.charAt(i) == '[') stack.push('[');
                    else if (s.charAt(i) == ']') stack.pop();
                    sb.append(s.charAt(i));
                    i++;
                    if (stack.empty()) break;
                }
                sb.deleteCharAt(0);
                sb.deleteCharAt(sb.length() - 1);
                String decodedString = decodeString(sb.toString());
                decodedStrings.add(decodedString);
            }
            else { // 不带有重复次数
                repeats.add(1);
                StringBuilder sb = new StringBuilder();
                while (i < s.length() && !isNumber(s.charAt(i))) {
                    sb.append(s.charAt(i));
                    i++;
                }
                decodedStrings.add(sb.toString());
            }
        }

        StringBuilder sb = new StringBuilder();
        for (i = 0; i < repeats.size(); i++) {
            int repeat = repeats.get(i);
            for (int r = 0; r < repeat; r++) sb.append(decodedStrings.get(i));
        }

        return sb.toString();
    }

    private static boolean isNumber(char ch) {
        return ch - '0' >= 0 && ch - '0' <= 9;
    }

    public static void main(String[] args) {
        String s = "3[a]2[bc]";
        System.out.println(decodeString(s));
    }
}
